import React, { Component } from "react";
import InPageStopAnnouncement from "components/template/in-page-stop-announcement/in-page-stop-announcement";
import { Icon, Radio, Spin } from "antd";
import { deepCopy, messages, sortByProperty, eventTrack } from "share/common";
import "styles/dashboard/dashboard-refactor.scss";
import menuRoute from "routes/menuRoute";
import ShowStaffInfo from "containers/dashboard/dashboard-refactor-comp/show-staff-info";
import QuickTool from "containers/dashboard/dashboard-refactor-comp/quick-tool";
import DashboardCarousel from "containers/dashboard/dashboard-refactor-comp/dashboard-carousel";
import DynamicDocuments from "containers/dashboard/dashboard-refactor-comp/dynamic-documents";
import BusinessTravel from "containers/dashboard/dashboard-refactor-comp/business-travel";
import BusinessCard from "containers/dashboard/dashboard-refactor-comp/business-card";
import Report from "containers/dashboard/dashboard-refactor-comp/report";
import Muuri from "muuri";
import { connect } from "react-redux";
import homeService from "../home/home.service";
import baseService from "share/base.service";
import DashboardService from "containers/dashboard/dashboard.service";
import Condition from "components/condition";
import SlideFrame from "components/slide-frame";
import ComponentSwitcher from "containers/dashboard/dashboard-refactor-comp/component-switcher";
import debounce from "lodash.debounce";
import MaskGuide from "components/template/main-init-modal-manage/mask-guide/mask-guide";
import {
  DashBoard_2_0,
  DASHBOARD_DRAG_2_0,
} from "components/template/main-init-modal-manage/mask-guide/mask-guide.modal";
import moment from "moment";

const { If, Else } = Condition;

class DashboardRefactor extends Component {
  constructor(props) {
    super(props);
    this.state = {
      currentConfig: deepCopy(DashBoard_2_0),
      showMaskGuide: false,
      layoutLoading: false,
      enableDrag: false,
      objectType: "USER", //页面布局 生效范围 默认 仅自己
      layout: [],
    };
    this.apiFlag = false;
    this.grid = null;
    this.refMap = {
      showChartAnalysisExp: "dashboardReportRef",
      showBillDynamicStateExp: "dynamicDocumentsRef",
    };
    this.resetLayout = debounce(() => {
      this.compareData(DashboardService.newDefaultLayout);
    }, 300);
    this.restoreData = debounce(this.restoreData, 300);
    this.handleGuide = debounce(this.handleGuide, 300);
  }

  componentWillMount() {
    if (sessionStorage.getItem("hly.layout.sync") === "true") {
      const layout = localStorage.getItem("hly.layout");
      this.setState({ layoutLoading: false, layout: JSON.parse(layout) }, this.initMuuri);
    } else {
      this.getOnlineLayout();
      this.setState({ layoutLoading: true });
    }
  }

  componentDidMount() {}

  componentWillUnmount() {}

  handleGuide = () => {
    const initDone = sessionStorage.getItem("hly.init.done");
    const finishedGuide = localStorage.getItem("hly.guide") ? JSON.parse(localStorage.getItem("hly.guide")) : [];
    if (finishedGuide.indexOf("NEW_DASHBOARD_GUIDE") > -1) return;
    if (!initDone) {
      sessionStorage.setItem("hly.un-guide", "NEW_DASHBOARD_GUIDE");
      return;
    } //初始化 7层 引导没有走完
    this.setState({ showMaskGuide: true }, () => {
      finishedGuide.push("NEW_DASHBOARD_GUIDE");
      localStorage.setItem("hly.guide", JSON.stringify([...finishedGuide]));
    });
  };

  handleDragGuide = (force = false) => {
    const finishedGuide = localStorage.getItem("hly.guide") ? JSON.parse(localStorage.getItem("hly.guide")) : [];
    if (finishedGuide.indexOf("NEW_DRAG_GUIDE") > -1 && !force) return;
    this.setState({ showMaskGuide: true, currentConfig: deepCopy(DASHBOARD_DRAG_2_0) }, () => {
      if (force) {
        finishedGuide.indexOf("NEW_DRAG_GUIDE") > -1
          ? finishedGuide.splice(finishedGuide.indexOf("NEW_DRAG_GUIDE"), 1)
          : "";
      }
      finishedGuide.push("NEW_DRAG_GUIDE");
      localStorage.setItem("hly.guide", JSON.stringify([...finishedGuide]));
    });
  };

  getOnlineLayout = () => {
    DashboardService.getMyLayout().then((res) => {
      if (res.data && res.data.customizedPageConfigs) {
        const layout = res.data && res.data.customizedPageConfigs;
        const lastUpdatedDate = res.data.lastUpdatedDate;
        const oldSetting = !moment("2020-12-18 23:59:59").isBefore(moment(lastUpdatedDate));
        if (oldSetting) {
          //如果拿到的配置 是 迭代2020-12-18以前设置的数据，默认给新版页面的布局
          this.useDefault();
        } else {
          localStorage.setItem("hly.layout", JSON.stringify(layout));
          sessionStorage.setItem("hly.layout.sync", "true");
          this.setState({ layout, layoutLoading: false }, this.initMuuri);
        }
      } else {
        //无个人设置或租户设置 直接给默认
        this.useDefault();
      }
    });
  };

  useDefault = () => {
    localStorage.setItem("hly.layout", JSON.stringify(DashboardService.newDefaultLayout));
    sessionStorage.setItem("hly.layout.sync", "true");
    this.setState({ layout: DashboardService.newDefaultLayout, layoutLoading: false }, this.initMuuri);
  };

  handleMaskResize = () => {
    this.setState({ showMaskGuide: false }, () => {
      setTimeout(() => {
        this.setState({ showMaskGuide: true });
      }, 300);
    });
  };

  initMuuri = () => {
    this.grid = new Muuri(".dashboard-content-box", {
      dragEnabled: true,
      layoutOnResize: true,
      dragSortPredicate: {
        threshold: 50,
        action: "move",
      },
      dragStartPredicate: this.dragStartPredicate,
      dragPlaceholder: {
        enabled: true,
      },
      itemPlaceholderClass: "card-placeholder",
      itemReleasingClass: "card-releasing",
      itemDraggingClass: "card-dragging",
    });
    this.handleGuide();
  };

  getMuuriItemKeyArray = (grid) => {
    const itemIds = grid.getItems().map((item) => {
      return item.getElement().getAttribute("data-id");
    });
    return itemIds;
  };

  dragStartPredicate = (item, event) => {
    const { enableDrag } = this.state;
    if (!enableDrag) {
      return false;
    }
    return Muuri.ItemDrag.defaultStartPredicate(item, event);
  };

  handleDragComp = () => {
    const { tenant } = this.props;
    this.setState({ enableDrag: !this.state.enableDrag }, this.handleDragGuide);
    eventTrack({
      category: "1218-新首页-埋点",
      action: "点击了设置首页面板",
      label: tenant.tenantName,
    });
  };

  hideExample = (key) => {
    const { userOtherSetting } = this.props.user;
    userOtherSetting[key] = false;
    homeService.setExampleStatus(userOtherSetting).then((res) => {
      this[this.refMap[key]] && this[this.refMap[key]].setLoading();
      baseService.getUser().then(() => {
        this[this.refMap[key]] && this[this.refMap[key]].getRealData();
      });
    });
  };

  viewGuide = () => {
    this.handleDragGuide(true);
  };

  openCompSwitcher = () => {
    const layout = JSON.parse(localStorage.getItem("hly.layout"));
    SlideFrame.open(
      {
        title: messages("common-1.key302") /*模块设置*/,
        content: ComponentSwitcher,
        afterClose: (resultLayout) => {
          this.compareData(resultLayout, true);
        },
        params: { layout },
      },
      this
    );
  };

  restoreData = () => {
    this.compareData(DashboardService.newDefaultLayoutHide);
    this.resetLayout();
    eventTrack({
      category: "1218-新首页-埋点",
      action: "设置面板-恢复默认布局",
      label: this.props.tenant.tenantName,
    });
  };

  compareData = (resultLayout, sendData = false) => {
    if (!resultLayout) return;
    const layout = JSON.parse(localStorage.getItem("hly.layout"));
    const deleteArray = [];
    const addArray = [];
    layout.forEach((item) => {
      const target = resultLayout.find((find) => {
        return item.key === find.key;
      });
      if (target.show !== item.show) {
        if (item.show) {
          deleteArray.push(target);
        } else {
          addArray.push(target);
        }
      }
    });
    deleteArray.forEach((deleteItem) => {
      const _deleteItem = this.grid.getItems().filter((filterItem) => {
        return filterItem.getElement().getAttribute("data-id") === `home-${deleteItem.key}`;
      });
      this.grid.remove(_deleteItem, { removeElements: false });
    });
    this.setState({ layout: resultLayout }, () => {
      addArray.forEach((addItem) => {
        const items = this.grid.add(document.getElementById(`home-${addItem.key}`), {
          index: -1,
          active: false,
        });
        this.grid.show(items);
      });
      localStorage.setItem("hly.layout", JSON.stringify(resultLayout));
    });
    if (sendData) {
      eventTrack({
        category: "1218-新首页-埋点",
        action: "设置面板结果",
        label: `添加了：${addArray.map((item) => item.name).join(",")}; 关闭了：${deleteArray
          .map((item) => item.name)
          .join(",")}`,
      });
    }
  };

  RadioChange = (e) => {
    this.setState({ objectType: e.target.value });
  };

  saveLayoutToLocalAndServer = () => {
    const { layout, objectType } = this.state;
    const orderArray = this.getMuuriItemKeyArray(this.grid);
    const newLayout = [];
    layout.forEach((layoutItem, layoutIndex) => {
      orderArray.forEach((newOrder, orderIndex) => {
        if (layoutItem.key === newOrder.split("-")[1]) {
          layoutItem.order = orderIndex;
          layoutItem.show = true;
          newLayout.push(layoutItem);
        }
      });
    });
    const other = layout.filter((item) => {
      return !newLayout.find((newItem) => {
        return item.key === newItem.key;
      });
    });
    other.forEach((item, index) => {
      item.order = newLayout.length + index;
      item.show = false;
    });
    const result = sortByProperty(newLayout.concat(other), "order");
    const params = {
      objectType,
      customizedPageConfigs: result,
    };
    if (!this.apiFlag) {
      this.apiFlag = true;
      DashboardService.updateMyLayout(params)
        .then((res) => {
          this.setState({ enableDrag: false, objectType: "USER" });
          localStorage.setItem("hly.layout", JSON.stringify(result));
          this.apiFlag = false;
        })
        .catch((err) => {
          this.apiFlag = false;
        });
      eventTrack({
        category: "1218-新首页-埋点",
        action: `以【${objectType === "TENANT" ? "针对全租户" : "仅对个人"}】方式完成了首页配置`,
        label: this.props.tenant.tenantName,
      });
    }
  };

  renderComponents = () => {
    const { layoutLoading, layout, enableDrag } = this.state;
    const { loginUser, user, tenant, menuTree } = this.props;
    const { userOtherSetting = {} } = user;
    const { showBillDynamicStateExp, showChartAnalysisExp } = userOtherSetting;
    const trialTenant = !["REAL"].includes(tenant.licenseType); //除正式外的 所以其他类型 ）租户(试用/内部测试)
    const newHomeKeyList = ["0", "2", "3", "5", "8", "9"];
    const showList = layout.filter((item) => {
      return newHomeKeyList.includes(item.key);
    });
    if (layoutLoading) {
      return (
        <Spin spinning>
          <div className="loading-box" />
        </Spin>
      );
    }
    return (
      <div className={`dashboard-content-box ${enableDrag ? "enable-drag" : ""}`}>
        {showList.map((item) => {
          if (item.show) {
            if (item.key === "0") {
              return (
                <DashboardCarousel tenant={tenant} enableDrag={enableDrag} uniKey={item.key} loginUser={loginUser} />
              );
            } else if (item.key === "2") {
              return (
                <QuickTool
                  enableDrag={enableDrag}
                  menuTree={menuTree}
                  uniKey={item.key}
                  user={loginUser}
                  tenant={tenant}
                />
              );
            } else if (item.key === "3") {
              return (
                <DynamicDocuments
                  enableDrag={enableDrag}
                  menuTree={menuTree}
                  uniKey={item.key}
                  tenant={tenant}
                  onRef={(ref) => (this.dynamicDocumentsRef = ref)}
                  trialTenant={trialTenant && showBillDynamicStateExp}
                  onConfirm={() => {
                    this.hideExample("showBillDynamicStateExp");
                  }}
                />
              );
            } else if (item.key === "5") {
              return (
                <Report
                  enableDrag={enableDrag}
                  uniKey={item.key}
                  tenant={tenant}
                  onRef={(ref) => (this.dashboardReportRef = ref)}
                  trialTenant={trialTenant && showChartAnalysisExp}
                  onConfirm={() => {
                    this.hideExample("showChartAnalysisExp");
                  }}
                />
              );
            } else if (item.key === "8") {
              return <BusinessCard uniKey={item.key} />;
            } else if (item.key === "9") {
              return <BusinessTravel enableDrag={enableDrag} tenant={tenant} menuTree={menuTree} uniKey={item.key} />;
            }
          }
        })}
      </div>
    );
  };

  renderMask = () => {
    const { showMaskGuide, currentConfig } = this.state;
    if (showMaskGuide) {
      return (
        <MaskGuide
          config={currentConfig}
          onResize={this.handleMaskResize}
          onClose={() => {
            this.setState({ showMaskGuide: false });
            eventTrack({
              category: "1218-新首页-埋点",
              action: currentConfig.key === "dashboard" ? "完成了个人首页引导" : "完成了设置首页面板操作引导",
              label: this.props.tenant.tenantName,
            });
          }}
        />
      );
    }
    return <span />;
  };

  render() {
    const { menuTree, tenant } = this.props;
    const { enableDrag, objectType } = this.state;
    const url = menuRoute.getPageUrlByKey("home");
    return (
      <div className="dashboard-refactor full-height-page-88 full-page-margin" id={"dashboard-scroll-container"}>
        <div className={"dashboard-head-box"}>
          <div className="max-wrapper">
            <InPageStopAnnouncement />
            <Condition>
              {/*操作选项*/}
              <If value={enableDrag}>
                <div className="operate-box">
                  <div className="operate">
                    <h2>{messages("basic-1.key142") /*首页面板设置与隐藏*/}</h2>
                    <p style={{ marginBottom: 0 }}>
                      <span id={"operate-item-guide-id"} className="operate-item" onClick={this.openCompSwitcher}>
                        <Icon type="tool" />
                        {messages("basic-1.key143") /*设置可见模块*/}
                      </span>
                      <span className="operate-item" onClick={this.restoreData}>
                        <Icon type="export" style={{ transform: "rotate(180deg)" }} />
                        {messages("basic-1.key144") /*恢复默认布局*/}
                      </span>
                      <span className="operate-item" onClick={this.viewGuide}>
                        <Icon type="bars" />
                        {messages("basic-1.key145") /*查看操作引导*/}
                      </span>
                    </p>
                  </div>
                  <div className="save-exit">
                    <If value={menuTree.allAPIMenuItem.home}>
                      <Radio.Group className="Group" value={objectType} onChange={this.RadioChange}>
                        <Radio value={"TENANT"}>{messages("basic-1.key148") /*全租户生效*/}</Radio>
                        <Radio value={"USER"}>{messages("basic-1.key149") /*仅自己生效*/}</Radio>
                      </Radio.Group>
                    </If>
                    <span
                      id={"finish-and-save-guide-id"}
                      className="finish-and-save operate-item"
                      onClick={this.saveLayoutToLocalAndServer}
                    >
                      {messages("basic-1.key150") /*完成并退出*/}
                      <Icon type="login" />
                    </span>
                  </div>
                </div>
              </If>
              {/*个人信息*/}
              <Else>
                <div className="title-and-switch">
                  <div className="home-title">{messages("basic-1.key233") /*个人首页*/}</div>
                  <div className="edit-button-group">
                    {menuTree.keyUrl.home && (
                      <div
                        className="page-change-url"
                        onClick={() => {
                          this.context.router.push(url);
                          sessionStorage.setItem("hly.tempHome", "home");
                        }}
                      >
                        <Icon type="swap" />
                        <span>&nbsp;{messages("basic-1.key146") /*切换到管理员首页*/}</span>
                      </div>
                    )}
                    <div className="page-change-url" ref="settingBtn" onClick={this.handleDragComp}>
                      <Icon type="setting" />
                      <span>&nbsp;{messages("basic-1.key147") /*设置首页面板*/}</span>
                    </div>
                  </div>
                </div>
                <ShowStaffInfo tenant={tenant} />
              </Else>
            </Condition>
          </div>
          {this.renderMask()}
        </div>
        {this.renderComponents()}
      </div>
    );
  }
}

DashboardRefactor.propTypes = {};

DashboardRefactor.contextTypes = {
  router: React.PropTypes.object,
};

function mapStateToProps(state) {
  return {
    loginUser: state.login.loginUser,
    tenant: state.login.tenant,
    authToken: state.main.authToken,
    language: state.main.language,
    user: state.login.user,
    menuTree: state.login.menuTree,
  };
}

export default connect(mapStateToProps)(DashboardRefactor);
